package main

import (
	"blog/config"
	"blog/database"
	"blog/internal/controller"
	"blog/internal/model"
	"blog/internal/repository"
	"blog/internal/router"
	"blog/internal/service"
	"log"
	"strconv"
)

func main() {
	// 加载配置
	cfg, err := config.Load("config/config.yaml")
	if err != nil {
		log.Fatalf("failed to load config: %v", err)
	}

	// 初始化数据库
	db, err := database.Connect(cfg)
	if err != nil {
		log.Fatalf("failed to connect database: %v", err)
	}

	// 自动迁移模型
	if err := db.AutoMigrate(&model.Article{}); err != nil {
		log.Fatalf("failed to migrate database: %v", err)
	}

	// 初始化仓库
	articleRepo := repository.NewArticleRepository(db)

	// 初始化服务
	articleService := service.NewArticleService(articleRepo)

	// 初始化控制器
	articleCtrl := controller.NewArticleController(articleService)

	// 设置路由
	r := router.SetupRouter(articleCtrl)

	// 启动服务器
	if err := r.Run(":" + strconv.Itoa(cfg.Server.Port)); err != nil {
		log.Fatalf("failed to start server: %v", err)
	}
}
